package com.ulic.customerManApplication.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


public class UserContextFilter implements Filter {
	protected FilterConfig filterConfig = null;
	private String redirectURL = null;
	private String sessionKey = null;

	public void doFilter(ServletRequest servletRequest,
			ServletResponse servletResponse, FilterChain filterChain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;
		String url = request.getRequestURL().toString();

		HttpSession session = request.getSession();
		if (sessionKey == null) {
			filterChain.doFilter(request, response);
			return;
		}
		if (url.indexOf("login.do") < 0 && url.indexOf("index.jsp") < 0&&url.indexOf("downloadSign.do")<0&&url.indexOf("sign.do")<0&&url.indexOf("admin.do")<0
				&& session.getAttribute(sessionKey) == null) {
			response.sendRedirect(request.getContextPath() +redirectURL);
			return;
		} 
		filterChain.doFilter(servletRequest, servletResponse);
	}

	public void destroy() {
	}

	public void init(FilterConfig filterConfig) throws ServletException {
		this.filterConfig = filterConfig;
		redirectURL = filterConfig.getInitParameter("redirectURL");
		sessionKey = filterConfig.getInitParameter("checkSessionKey");
		//adminSessionKey = filterConfig.getInitParameter("checkAdminSessionKey");
	}
}
